package com.dyzx.hbb.common.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

import com.dyzx.hbb.common.mybatis.SelectBuilder;
import com.dyzx.hbb.common.utils.DateFormat;
import com.dyzx.hbb.modules.fcxs.sql.FcxsSqlHelper;
import com.dyzx.hbb.modules.sys.sql.SqlHelper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;


import org.apache.commons.lang3.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;

public class MyLambdaQueryWrapper<T> extends AbstractLambdaWrapper<T, MyLambdaQueryWrapper<T>>
        implements Query<MyLambdaQueryWrapper<T>, T, SFunction<T, ?>> {

    private SelectBuilder sqlSelect = new SelectBuilder();


    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(entity)
     */
    public MyLambdaQueryWrapper() {
        this((T) null);
        System.out.println("entityClass  sssssssssssssssssssssssssssssssss");

    }

    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(entity)
     */
    public MyLambdaQueryWrapper(T entity) {
        super.setEntity(entity);
        super.initNeed();



    }

    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(entity)
     */
    public MyLambdaQueryWrapper(Class<T> entityClass) {
        super.setEntityClass(entityClass);
        super.initNeed();
        System.out.println("entityClass  sssssssssssssssssssssssssssssssss"+entityClass);

    }

    /**
     * 不建议直接 new 该实例，使用 Wrappers.lambdaQuery(...)
     */
    MyLambdaQueryWrapper(T entity, Class<T> entityClass, SelectBuilder sqlSelect, AtomicInteger paramNameSeq,
                         Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
                         SharedString lastSql, SharedString sqlComment, SharedString sqlFirst) {
        super.setEntity(entity);
        super.setEntityClass(entityClass);
        this.paramNameSeq = paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
        this.sqlSelect = sqlSelect;
        this.lastSql = lastSql;
        this.sqlComment = sqlComment;
        this.sqlFirst = sqlFirst;
        TableName tableName = entityClass.getAnnotation(TableName.class);
        System.out.println("TableName  sssssssssssssssssssssssssssssssss"+tableName.value());
        System.out.println(tableName.value());

    }

    /**
     * SELECT 部分 SQL 设置
     *
     * @param columns 查询字段
     */
    @SafeVarargs
    @Override
    public final MyLambdaQueryWrapper<T> select(SFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            this.sqlSelect.getParts().add(columnsToString(columns).toLowerCase());
        }

        return typedThis;
    }

    @SafeVarargs
    public final MyLambdaQueryWrapper<T> selectNotNull(SFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {

            String lowerCase = columnsToString(columns).toLowerCase();
            this.sqlSelect.getParts().add("IF("+columnsToString(columns)+"='',NULL,"+columnsToString(columns)+") AS "+lowerCase);
            //  this.sqlSelect.getParts().add(lowerCase);
        }

        return typedThis;
    }
/*    @SafeVarargs
    @Override
    public final MyLambdaQueryWrapper<T> select(SFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            String lowerCase = columnsToString(columns).toLowerCase();
            //  this.sqlSelect.getParts().add("IF("+columnsToString(columns)+"='',NULL,"+columnsToString(columns)+") AS "+lowerCase);
            this.sqlSelect.getParts().add(lowerCase);
        }

        return typedThis;
    }
    public  MyLambdaQueryWrapper<T> selectNotNull(SFunction<T, ?>... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            String lowerCase = columnsToString(columns).toLowerCase();
            this.sqlSelect.getParts().add("IF("+columnsToString(columns)+"='',NULL,"+columnsToString(columns)+") AS "+lowerCase);
            //  this.sqlSelect.getParts().add(lowerCase);
        }

        return typedThis;
    }*/
    @Override
    public MyLambdaQueryWrapper<T> select(boolean condition, List<SFunction<T, ?>> columns) {

        if (condition && CollectionUtil.isNotEmpty(columns)) {
           return this.select(columns);
        }
        return typedThis;
    }

    /**
     * 过滤查询的字段信息(主键除外!)
     * <p>例1: 只要 java 字段名以 "test" 开头的             -> select(i -&gt; i.getProperty().startsWith("test"))</p>
     * <p>例2: 只要 java 字段属性是 CharSequence 类型的     -> select(TableFieldInfo::isCharSequence)</p>
     * <p>例3: 只要 java 字段没有填充策略的                 -> select(i -&gt; i.getFieldFill() == FieldFill.DEFAULT)</p>
     * <p>例4: 要全部字段                                   -> select(i -&gt; true)</p>
     * <p>例5: 只要主键字段                                 -> select(i -&gt; false)</p>
     *
     * @param predicate 过滤方式
     * @return this
     */
    @Override
    public MyLambdaQueryWrapper<T> select(Class<T> entityClass, Predicate<TableFieldInfo> predicate) {
        if (entityClass == null) {
            entityClass = getEntityClass();
        } else {
            setEntityClass(entityClass);
        }
        TableName tableName = entityClass.getAnnotation(TableName.class);
        System.out.println("TableName  sssssssssssss1ssssssssssssssssssss"+tableName.value());

        Assert.notNull(entityClass, "entityClass can not be null");
        this.sqlSelect.getParts().add(TableInfoHelper.getTableInfo(entityClass).chooseSelect(predicate));
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> select(String... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            //   System.out.println("-------------------SSLSELECT----------------------");
            String join = String.join(",", columns);
            //  join=join.replaceAll("as x","");
            this.sqlSelect.getParts().add(join.toLowerCase());
            //  this.sqlSelect.setStringValue(String.join(",", columns));
        }

        return this.typedThis;
    }

    @Override
    public String getSqlSelect() {
        return sqlSelect.getStringValue();
    }

    /**
     * 用于生成嵌套 sql
     * <p>故 sqlSelect 不向下传递</p>
     */
    @Override
    protected MyLambdaQueryWrapper<T> instance() {
        return new MyLambdaQueryWrapper<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs,
                new MergeSegments(), SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString());
    }

    @Override
    public void clear() {
        super.clear();
        sqlSelect.toNull();
    }

// =================== 上面的代码都是照抄的   =====================

    public MyLambdaQueryWrapper<T> findInSet(SFunction<T, ?> column, String params) {
        if (column != null) {

            this.apply(StringUtils.isNotEmpty(params), "FIND_IN_SET(" + columnToString(column) + ",'" + params + "')");
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T> findInSet(boolean condition,SFunction<T, ?> column, String params) {
        if (condition) {

           return findInSet(column, params);
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T>  inSet(boolean condition,SFunction<T, ?> column, String params) {
        if (condition) {

            return inSet(column, params);
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T> inSet(SFunction<T, ?> column, String params) {
        if (column != null) {

          this.in(column, (Object) params.split(","));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> min(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("min(%s)", columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> max(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("max(%s)", columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> sum(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("IFNULL(sum(%s),0)", columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> avg(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("round(IFNULL(avg(%s),0))", columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> count(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format("count(%s)", columnToString(column)));
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T> as(String asName) {
        if (StringUtils.isEmpty(asName)) {
            return typedThis;
        }

        List<String> parts = this.sqlSelect.getParts();

        if (CollectionUtil.isEmpty(parts)) {
            return typedThis;
        }

        String lastPart = parts.remove(parts.size() - 1);
        lastPart += " as " + asName;

        parts.add(lastPart);


        return typedThis;
    }
    public MyLambdaQueryWrapper<T>
    imageUrl(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getImageUrl("%s"), columnToString(column)));
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T>
    imageUrls(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getImageUrls("%s"), columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> deptName(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getDeptName("%s"), columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> organName(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getOrganName("%s"), columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> orgNameSql(String column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getOrganName("%s"), column));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> userName(SFunction<T, ?> column) {
        if (column != null) {

            this.sqlSelect.getParts().add(String.format(SqlHelper.getUserName("%s"), columnToString(column)));
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T> userNameSql(String column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getUserName("%s"), column));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> dateBetween(boolean condition,SFunction<T, ?> column, DateFormat dateFormat, String createDate) {
        if (condition && createDate.contains("~")) {

            return dateBetween(column, dateFormat, createDate);
        }
        return typedThis;
    }
    public MyLambdaQueryWrapper<T> dateBetween(SFunction<T, ?> column, DateFormat dateFormat, String createDate) {
        if (column != null && createDate.contains("~")) {
            String[] split = createDate.split("~");
            DateTime parse = DateUtil.parse(split[0]);
            Date startDate = parse.toSqlDate();

            DateTime parse2 = DateUtil.parse(split[1]);
            Date endDate = parse2.toSqlDate();
            //columnToString(column)
            String fs = "";
            String fe = "";

            if (dateFormat.getType() == 1) {
                fs = DateUtil.format(startDate, DateFormat.J_DATE_TIME.getName());
                fe = DateUtil.format(endDate, DateFormat.J_DATE_TIME.getName());
            }
            if (dateFormat.getType() == 2) {
                fs = DateUtil.format(startDate, DateFormat.J_DATE.getName());
                fe = DateUtil.format(endDate, DateFormat.J_DATE.getName());
            }
            if (dateFormat.getType() == 3) {
                fs = DateUtil.format(startDate, DateFormat.J_DATE_MONTH.getName());
                fe = DateUtil.format(endDate, DateFormat.J_DATE_MONTH.getName());
            }
            if (dateFormat.getType() == 4) {
                fs = DateUtil.format(startDate, DateFormat.J_DATE_YEAR.getName());
                fe = DateUtil.format(endDate, DateFormat.J_DATE_YEAR.getName());
            }

            typedThis.apply("(date_format(FROM_UNIXTIME(" + columnToString(column) + "/1000),'" + dateFormat.getName() + "') >='" + fs + "' and date_format(FROM_UNIXTIME(" + columnToString(column) + "/1000),'" + dateFormat.getName() + "') <='" + fe + "')");
        }
        return typedThis;
    }


    public MyLambdaQueryWrapper<T> addressName(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getAddressName("%s"), columnToString(column)));
        }
        return typedThis;
    }


    public MyLambdaQueryWrapper<T> brokerName(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getBrokerName("%s"), columnToString(column)));
        }
        return typedThis;
    }


    public MyLambdaQueryWrapper<T> brokersName(SFunction<T, ?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getBrokersName("%s"), columnToString(column)));
        }
        return typedThis;
    }



    public MyLambdaQueryWrapper<T> fcxsOrderNo(SFunction<T, ?> column) {
        if (column != null) {
           this.typedThis.sqlSelect.getParts().add(String.format(FcxsSqlHelper.getOrderNo("%s"), columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> byFcxsOrderNo(boolean b, SFunction<T, ?> column, String str) {
        if(b){
            return byFcxsOrderNo(column,str);
        }

        return typedThis;
    }

    private MyLambdaQueryWrapper<T> byFcxsOrderNo(SFunction<T,?> column, String str) {
        if (column != null) {
            this.typedThis.inSql(column,FcxsSqlHelper.byOrderNo(str));
        }
        return typedThis;
    }



    public MyLambdaQueryWrapper<T> fcxsClueNo(SFunction<T,?> column) {
        if (column != null) {
            this.typedThis.sqlSelect.getParts().add(String.format(FcxsSqlHelper.getClueNo("%s"), columnToString(column)));
        }
        return typedThis;
    }


    public MyLambdaQueryWrapper<T> houseName(SFunction<T,?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getHouseName("%s"), columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> wmsProductName(SFunction<T,?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getWmsProductName("%s"), columnToString(column)));
        }
        return typedThis;
    }

    public MyLambdaQueryWrapper<T> houseLeaderName(SFunction<T,?> column) {
        if (column != null) {
            this.sqlSelect.getParts().add(String.format(SqlHelper.getUserName("("+SqlHelper.getHouseLeaderId("%s")+")"), columnToString(column)));
        }
        return typedThis;
    }



}
